package com.bdqn.shiro;

import com.bdqn.pojo.Right;
import com.bdqn.pojo.Role;
import com.bdqn.pojo.User;
import com.bdqn.service.RightService;
import com.bdqn.service.RoleService;
import com.bdqn.service.UserService;
import jakarta.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.lang.util.ByteSource;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.context.annotation.Lazy;

import java.util.Set;


/**
 * MyShiroRealm（安全数据源）
 *
 * @author LILIBO
 * @since 2024-10-15
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Lazy // Shiro框架执行比@Cacheable注解AOP代理早，导致对象代理不成功
    @Resource
    private UserService userService;

    @Lazy // Shiro框架执行比@Cacheable注解AOP代理早，导致对象代理不成功
    @Resource
    private RoleService roleService;

    @Lazy // Shiro框架执行比@Cacheable注解AOP代理早，导致对象代理不成功
    @Resource
    private RightService rightService;

    /**
     * 自定义认证流程（机制）
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用 MyShiroRealm.doGetAuthenticationInfo 获取身份信息！");
        // 获得身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName = token.getUsername();

        // 从数据库中根据用户名查询用户对象（联表查询，包含角色信息）
        User user = userService.getByUsrName(userName);
        if (user == null) {
            throw new UnknownAccountException("用户不存在"); // 用户不存在
        }
        if (user.getUsrFlag() == null || user.getUsrFlag() == 0) {
            throw new LockedAccountException("账号已锁定");
        }
        // 通过用户获取角色信息
        Role role = user.getRole(); // int &207 -> list
        // 根据角色获取权限列表
        Set<Right> rights = rightService.findRightByRoleId(role.getRoleId());
        // 给角色设置权限集合
        role.setRights(rights);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getUsrPassword(), ByteSource.Util.bytes("czkt"), this.getName());
        // 返回身份信息
        return info;
    }

    /**
     * 自定义授权（认证通过才会授权）
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用 MyShiroRealm.doGetAuthorizationInfo 获取权限信息！");
        // 获得权限信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 静态授权：授予主体(用户)相应的角色和权限
        /*
        info.addRole(user.getRole().getRoleName());
        info.addStringPermission("用户列表"); // 所有用户拥有"用户列表"权限
        if ("管理员".equals(user.getRole().getRoleName())) { // 管理员拥有"增删改"权限
            info.addStringPermission("用户添加");
            info.addStringPermission("用户编辑");
            info.addStringPermission("用户删除");
        }
        */
        // 动态授权：从数据库中获取角色和权限
        // Role role = user.getRole();
        Role role = roleService.getByUserId(user.getUsrId()); // 用户对应角色关系变化时及时刷新
        if (role != null) {
            info.addRole(role.getRoleName()); // 动态设置角色
            // Set<Right> rights = role.getRights();
            Set<Right> rights = rightService.findRightByRoleId(role.getRoleId()); // 角色对应权限关系变化时及时刷新
            if (rights != null && !rights.isEmpty()) {
                for (Right right : rights) {
                    info.addStringPermission(right.getRightCode()); // 动态设置权限
                }
            }
        }
        // 返回授权信息
        return info;
    }

    /**
     * 清空当前认证用户权限缓存
     */
    public void clearMyCachedAuthorizationInfo() {
        clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

    /**
     * 清空所有用户权限缓存
     */
    public void clearAllCachedAuthorizationInfo() {
        if (this.isAuthorizationCachingEnabled()) { // 权限缓存是否可用
            Cache<Object, AuthorizationInfo> cache = null;
            CacheManager cacheManager = this.getCacheManager();
            if (cacheManager != null) {
                String cacheName = this.getAuthorizationCacheName(); // 获得权限缓存名称
                cache = cacheManager.getCache(cacheName); // 获得权限缓存
            }
            if (cache != null) {
                cache.clear(); // 清空
            }
        }
    }

}
